package com.ly.wxstore.service.weixin;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springside.modules.mapper.JsonMapper;

import com.ly.wxstore.entity.weixin.WeixinPublic;
import com.ly.wxstore.rest.dto.ReceiveAccessTokenDto;
import com.ly.wxstore.rest.dto.WeixinUserInfoDto;
import com.ly.wxstore.utils.HttpUtil;

/**
 * 微信OAuth2.0授权、认证Service
 * @author Peter
 *
 */
@Component
public class WeixinOAuthService {

	private static Logger logger = LoggerFactory.getLogger(WeixinOAuthService.class);
	
	private static JsonMapper mapper = JsonMapper.nonDefaultMapper();
	
	@Autowired
	private WeixinConf weixinConf;
	
	@Autowired
	private WeixinPublicService weixinPublicService;

	
	public static final String _SS="%3A%2F%2F";//  ://
	public static final String _S="%2F";       //   /
	
	public final static void main(String[] args) {
//		recieveCode();
		//receiveAccessToken("123");
	}
	
	/**
	 * 第二步 获取网页授权access_token(注意：此access_token与基础支持的access_token不同)
	 * //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
	 * @param code
	 * @return
	 */
	public ReceiveAccessTokenDto receiveAccessToken(String code){
		WeixinPublic weixinPublic = weixinPublicService.getGlobleWeixinPublic();
		
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+weixinPublic.getAppId()+"&secret="+weixinPublic.getAppSecret()+"&code="+code+"&grant_type=authorization_code";
		
		String body = HttpUtil.httpGet(url);
		logger.info("----------------------------------------/n--- 第二步 获取access_token {code:"+code+"} result:-->>"+body);
		ReceiveAccessTokenDto bean = mapper.fromJson(body, ReceiveAccessTokenDto.class);
		
	    return bean;
	}
	
	//	第四步 拉取用户信息(需scope为 snsapi_userinfo)
	public WeixinUserInfoDto receiveWeixinUserInfo(String access_token,String openid){
		String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
		
		String body = HttpUtil.httpGet(url);
		logger.info("----------------------------------------/n--- 第四步 拉取用户信息  result:-->>"+body);
		WeixinUserInfoDto bean = mapper.fromJson(body, WeixinUserInfoDto.class);
		
	    return bean;
	}
	
	
	//检验授权凭证（access_token）是否有效
	public boolean validateAccessToken(String accessToken,String openId){
		boolean valid = false;
		String url = "https://api.weixin.qq.com/sns/auth?access_token="+accessToken+"&openid="+openId;
		String body = HttpUtil.httpGet(url);
		ReceiveAccessTokenDto bean = mapper.fromJson(body, ReceiveAccessTokenDto.class);
		if("0".equals(bean.getErrcode())){
			valid = true;
		}
		
		return valid;
	}
}
